﻿using Code.Repsitory.MenuRoles;
using Code.Repsitory.Menus;
using Code.Repsitory.Roles;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;
using System.Security.Claims;

namespace CodeAPP.Auth
{
    /// <summary>
    /// 自定义授权过滤器
    /// </summary>
    public class CustomAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
    {

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            //实现自定义授权
            if (!context.HttpContext.User.Identity.IsAuthenticated)
            {
                context.Result = new StatusCodeResult(401);
            }

            //获取当前用户角色
            var roles = context.HttpContext.User.Claims.Where(m => m.Type == ClaimTypes.Role)
                        .Select(m => Convert.ToInt32(m.Value)).ToArray();

            //当前用户正在访问的Path
            var routeInfo = context.ActionDescriptor.AttributeRouteInfo.Template;

            //var serviceProvicer = context.HttpContext.Request;
            var serviceProvicer = context.HttpContext.RequestServices;
            var menuRoleRepo = serviceProvicer.GetService(typeof(IMenuRoleRepository)) as IMenuRoleRepository;
            var menuRepo = serviceProvicer.GetService(typeof(IMenuRepository)) as IMenuRepository;
            if (menuRoleRepo == null || menuRepo == null)
            {
                throw new Exception("IMenuRoleRepository获取失败");
            }

            //当前菜单的角色ID
            var list = menuRoleRepo.Queryable().Where
                        (m => m.MenuId == menuRepo.Queryable().Where(q => q.Route == routeInfo).First().MenuId)
                        .Select(m => m.RoleId).ToArray();

            //var list1 = menuRepo.Queryable().Join(menuRoleRepo.Queryable(), a => a.MenuId, b => b.MenuId, (a, b) => new { a, b })
            //            .Where(m => m.a.Route == routeInfo)
            //            .Select(m => m.b.RoleId)
            //            .ToArray();




            //[1,3]
            //[2,3,4,5,6]
            context.Result = new StatusCodeResult(403);
        }
    }
}
